package com.rpc.client;

import com.rpc.api.bean.RpcRequest;
import com.rpc.api.bean.RpcResponse;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;

public class RemoteInvocationHandler<T> implements InvocationHandler {

    private String interfaceClazz;

    public RemoteInvocationHandler(String interfaceClazz) {
        this.interfaceClazz = interfaceClazz;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setClazzName(interfaceClazz);
        rpcRequest.setMethodName(method.getName());
        rpcRequest.setValParams(args);

        Socket socket = new Socket("localhost", 9999);
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {

            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();

            RpcResponse rpcResponse = (RpcResponse) objectInputStream.readObject();

            return rpcResponse.getResult();

        }
    }
}
